import React, { useState }  from 'react';  
import { Form, Input, Button, Upload,message,Card,Table,Alert, Checkbox,Row,Col  } from 'antd';  
import { UploadOutlined,DownloadOutlined } from '@ant-design/icons';  
import { useTranslation } from 'react-i18next';  
import { CSSProperties } from 'react';  
import { createReport,editProduct,separatedFm,addFmReact,editFm,separatedFix,separatedCreateReport,subjectTestResult,updateSubjectTestResult,mixedfm,mixedFix,mixedCreateReport,getRmInciResult,saveSafetyRmInciResult,batchSaveRmInciResult,updateDataResult,uploadRemark,uploadRemarkUpdate,delRemark,refreshResult} from "@/api/modules/jhreport";
import './MergedCellsTable.css'; // 引入自定义的CSS样式 
import FullscreenLoading from '@/components/FullscreenLoading';
import {download} from '@/utils/request';

const FileUpload = ({ formData,tableData, onUploadSuccess }) => {  
  const [form] = Form.useForm();  
  const { t } = useTranslation();  
  const [uploading, setUploading] = useState(false);  
  const [fileList, setFileList] = useState([]); 
  const [errMsg,setErrMsg] = useState([]); 
  const [errCode,setErrCode] = useState('');
  const [percentMsg,setPercentMsg] = useState([]);
  const [functionMsg,setFunctionMsg] = useState([]);
  const [inciCnMsg,setInciCnMsg] = useState([]);
  const [rawData,setRawData] = useState([])
  const [showCoverCheckbox, setShowCoverCheckbox] = useState(false);  
  const [fm_isCover1,setIsCover] = useState(false); 
  const [fm_isFunction1,setIsFunction] = useState(false) 
  const [showConfirmCheckbox, setShowConfirmCheckbox] = useState(false);  
  const [showErrorTitle, setShowErrorTitle] = useState(false);  
  const [loading, setLoading] = useState(false); 

  // 初始设置表单值  
  React.useEffect(() => {  
    console.log(tableData,'tableData')
    if(tableData == undefined || tableData == "" || tableData == null){
    }else{
        formData.fm_name=tableData.fmName
        setRawData(tableData.rawTsData)
    }
    formData.fm_isCover = false
    formData.fm_isFunction = false
    form.setFieldsValue(formData);

  }, [form, formData]);  
  

  

  const columns = [  
    {  
        title: t('report.RMSerial'),  
        dataIndex: '原料序号',  
        key: '原料序号',  
        onCell: (_, index) => {
            const data = getSpanArr(rawData,'原料序号','原料序号')
            return {rowSpan : data[index]};
          }, 
      }, 
      {  
        title: t('report.RMCode'),  
        dataIndex: '原料Code',  
        key: '原料Code',  
        onCell: (_, index) => {
            const data = getSpanArr(rawData,'原料序号','原料Code')
            return {rowSpan : data[index]};
          },   
      }, 
      {  
        title: t('report.RMName'),  
        dataIndex: '原料名',  
        key: '原料名', 
        onCell: (_, index) => {
            const data = getSpanArr(rawData,'原料序号','原料名')
            return {rowSpan : data[index]};
          },   
      }, 
      {  
        title: t('report.INCICN'),  
        dataIndex: '标准中文名称INCI中文',  
        key: '标准中文名称INCI中文',  
      },  
    {  
      title: t('report.INCIEN'),  
      dataIndex: 'INCI名称INCI英文',  
      key: 'INCI名称INCI英文',  
    },  
    {  
      title:  t('report.RMPercentage'),  
      dataIndex: '原料含量%',  
      key: '原料含量%',   
      onCell: (_, index) => {
        const data = getSpanArr(rawData,'原料序号','原料含量%')
        return {rowSpan : data[index]};
      },  
    },  
    {  
        title: t('report.IngredientPercentageinRM'),  
        dataIndex: '原料中成分含量%',  
        key: '原料中成分含量%',  
      }, 
      {  
        title: t('report.Function'),  
        dataIndex: '使用目的',  
        key: '使用目的',  
      },
      {  
        title: t('report.remark'),  
        dataIndex: '备注',  
        key: '备注',  
      },
    // 可以根据需要添加更多列...  
  ];
  
  const getSpanArr =(data,dataIndex,dataIndex2) =>{
    let spanArr=[]
    let pos = 0
    // data就是我们从后台拿到的数据
    for (var i = 0; i < data.length; i++) {
      if (i === 0) {
        spanArr.push(1);
        pos= 0;
      } else {
        // 判断当前对象的指定属性值与上一个对象的指定属性值是否相等
        if (data[i][dataIndex] === data[i - 1][dataIndex] ) {
          if (data[i][dataIndex2] === data[i - 1][dataIndex2] ) {
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            pos = i;
          }
        }else{
          spanArr.push(1);
          pos = i;
        }
      }
    }
    return spanArr
  }

  const handleDownload = () => {  
    // 这里可以添加处理下载操作的逻辑，比如调用下载接口  
    download("/api/Ts/exportFmTemplate", {
      
    }, `Formula Template.xlsx`);
  };  

  const handleSubmit = async () => {  
    try {  
      // 验证表单  
      await form.validateFields();  
      // 假设我们从表单中获取文件和其他字段信息  
      const values = form.getFieldsValue();  
      const { file } = values;  
      setLoading(true)
      // 构造FormData对象  
      const formData1 = new FormData(); 
      if(values.file==null || values.file == undefined || values.file == ""){
            console.log(file,'file')
            onUploadSuccess('2',tableData)
            setLoading(false)
      }else{
        const file1 = values.file.originFileObj
        formData1.append('file',file1); // 假设file.file是选中的文件对象  
        // 可以继续添加其他表单字段  
        formData1.append("safety_product_id", formData.id);
        formData1.append("fm_number", values.fm_number);
        formData1.append("fm_name", values.fm_name);
        formData1.append("remark", values.fm_remark);
        formData1.append("isCover", formData.fm_isCover);
        formData1.append("isFunction", formData.fm_isFunction);
        console.log(formData1,'传输数据')
        // 设置上传状态为true  
        setUploading(true);  
        let check =1
                if(errMsg.length>0 && errCode=='2'){
                        if(values.fm_isCover==false){
                            check=0
                        }
                    }

                if(percentMsg.length>0){
                        if(values.fm_isFunction==false){
                            check=0
                        }
                      }
                if(functionMsg.length>0){
                        if(values.fm_isFunction==false){
                            check=0
                        }
                    }
                if(inciCnMsg.length>0){
                    if(values.fm_isFunction==false){
                            check=0
                        }
                }
                if(check==0){
                    message.error('表单提交失败，请看提示');  
                }
        // 发送POST请求到服务器  
        if(check==1){
            addFmReact(formData1).then(res=>{
                console.log(res.data.data,'rawData')
                localStorage.setItem('productId', res.data.data.id)
                const data = res.data.data
                setErrMsg(data.errMsg) 
                setPercentMsg(data.percentMsg) 
                setFunctionMsg(data.functionMsg) 
                setInciCnMsg(data.inciCnMsg) 
                setErrCode(data.errCode)
                setRawData(data.rawTsData)   //这个是我要获取的接口里面的数据  错误表单
                // 根据 errCode 更新显示状态  
                setShowCoverCheckbox(data.errCode === '2' && data.errMsg.length > 0);  
                setShowConfirmCheckbox(  
                (data.errCode === '2' && data.functionMsg.length > 0) ||  
                (data.errCode === '2' && data.percentMsg.length > 0) ||  
                (data.errCode === '2' && data.inciCnMsg.length > 0)  
                );  
                setShowErrorTitle(  
                data.percentMsg.length > 0 || data.functionMsg.length > 0 || data.inciCnMsg.length > 0  
                );  
                if (errCode == '1' || errCode == '2') {
                        //处理table
                        }
                        if (res.data.status == 0) {
                            //成功
                  
                            onUploadSuccess("2",res.data.data)
                            setLoading(false)
                            setUploading(false)
                        } else {
                            message.error('操作失败，请查看提示'); 
                            setUploading(false) 
                            setLoading(false)
                        }
            }).catch(()=>{
               
            })
        }
      }
        
    } catch (error) {  
      console.error('Form submission failed:', error);  
      message.error('表单提交失败，请检查输入内容');  
      setLoading(false)
      // 设置上传状态为false  
      setUploading(false);  
    }  
  };  
    
  const handleFileChange = (info) => { 
    console.log(info,'info') 
    info.file.status = "done"
    form.setFieldsValue({  
        file: info.file,  
      }); 
  };  

  const handleIsCoverCheckboxChange = (e) => {  
    setIsCover(e.target.checked); // 使用 setIsCover 函数来更新状态  
    formData.fm_isCover=e.target.checked
  };  

  const handleIsFunctionCheckboxChange = (e) => {  
    setIsFunction(e.target.checked); // 使用 setIsCover 函数来更新状态  
    formData.fm_isFunction=e.target.checked
  };  

  const beforeUpload = (file) => {  
    const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';  
    if (!isExcel) {  
      message.error('只能上传Excel文件（.xlsx）');  
      return false;  
    }  
    return true;  
  };  

  
  return (  
    <div>
    <FullscreenLoading showLoading={loading} loadingTip="Loading..."/> 
    <Card>
    <Form form={form} onFinish={handleSubmit} >  
      <Form.Item  
        name="fm_name" // 其他表单字段  
        label={t('report.formulaName')} 
        labelCol={{ style: { width: '120px', textAlign: 'left'  } }} // 使用内联样式替代类名
        rules={[{ required: true, message: '请输入配方名称！' }]}    
      >  
        <Input  style={{width:'400px'}}/>  
      </Form.Item>  
      <Form.Item  
        name="fm_number" // 其他表单字段  
        labelCol={{ style: { width: '120px', textAlign: 'left'  } }} // 使用内联样式替代类名
        label={t('report.formulaNumber')}  
      >  
        <Input  style={{width:'400px'}}/>  
      </Form.Item> 
      <Form.Item  
        name="file"  
        label="上传文件"  
        valuePropName="fileList"  
        labelCol={{ style: { width: '120px', textAlign: 'left'  } }} // 使用内联样式替代类名
        getValueFromEvent={({ fileList }) => fileList}  
      >  
        <Upload  
          customRequest={({ file, onSuccess, onError }) => {  
            // 这里是自定义上传逻辑，您可以根据实际需求实现上传逻辑  
            // 例如，使用axios发送POST请求上传文件  
            // 注意：这里的逻辑与表单提交时的文件上传是独立的，如果只需要在表单提交时上传，可以省略这部分  
          }}  
          beforeUpload={beforeUpload}  
          onChange={handleFileChange} 
        >  
          <Button icon={<UploadOutlined />}>{t('selectUpload')}</Button>  
        </Upload>  
        <Button icon={<DownloadOutlined></DownloadOutlined>} style={{marginTop:'2%'}} type="primary" onClick={handleDownload}>  
            {t('report.templateDownload')}  
          </Button>
      </Form.Item> 
   
      <Form.Item  
        name="fm_remark" // 其他表单字段
        labelCol={{ style: { width: '120px', textAlign: 'left'  } }} // 使用内联样式替代类名  
        label={t('report.remark')}  
      >  
        <Input.TextArea  style={{width:'400px'}}/>  
      </Form.Item> 
        {/* 根据percentMsg数组的长度判断是否渲染Card组件 */}  
    {(errMsg.length > 0 || inciCnMsg.length > 0 || functionMsg.length > 0 || percentMsg.length>0 ) && (
             <Alert  
             message={(errMsg.length > 0 || inciCnMsg.length > 0 || functionMsg.length > 0 || percentMsg.length>0 ) ? '有错误发生' : ''}  
             description={  
               <div>  
                 {showCoverCheckbox && (  
                   <Checkbox  
                     className="isCover"  
                     checked={fm_isCover1}  
                     onChange={handleIsCoverCheckboxChange} 
                   >  
                     覆盖原料code下的inci信息，以新上传为准  
                   </Checkbox>  
                 )}  
                 {errMsg.length > 0 && errCode == '2' &&(  
                   <h4 className="errorTtitle">有需要确认的覆盖信息，如下</h4>  
                 )}  
                  {errMsg.length > 0 && errCode == '1' &&(  
                   <h4 className="errorTtitle">有需要确认的错误信息，如下</h4>  
                 )} 
                 <ol>  
                   {errMsg.map((msg, index) => (  
                     <li key={index}>{msg}</li>  
                   ))}  
                 </ol>  
                 {showConfirmCheckbox && (  
                   <Checkbox  
                     className="isCover"  
                     checked={fm_isFunction1}  
                     onChange={handleIsFunctionCheckboxChange}  
                   >  
                     下面内容已确认,忽略提示  
                   </Checkbox>  
                 )}  
                 {showErrorTitle && (  
                   <div>  
                     <h4 className="errorTtitle">有可忽略的错误，如下</h4>  
                     {percentMsg.length > 0 && (  
                       <div>  
                         <span className="errorTtitle">实际成分含量错误:</span>  
                         <ol>  
                           {percentMsg.map((msg, index) => (  
                             <li key={index}>{msg}</li>  
                           ))}  
                         </ol>  
                       </div>  
                     )}  
                     {/* 类似地，可以添加 functionMsg 和 inciCnMsg 的显示逻辑 */}  
                     {functionMsg.length > 0 && (  
                       <div>  
                         <span className="errorTtitle">使用目的错误:</span>  
                         <ol>  
                           {functionMsg.map((msg, index) => (  
                             <li key={index}>{msg}</li>  
                           ))}  
                         </ol>  
                       </div>  
                     )}  
                        {inciCnMsg.length > 0 && (  
                       <div>  
                         <span className="errorTtitle">INCI中文名称错误:</span>  
                         <ol>  
                           {inciCnMsg.map((msg, index) => (  
                             <li key={index}>{msg}</li>  
                           ))}  
                         </ol>  
                       </div>  
                     )} 
                   </div>  
                 )}  
               </div>  
             }  
             type="error"  
             showIcon  
           /> 
    )}
     {(rawData.length > 0 ) && (
          <Table  
          columns={columns}  
          dataSource={rawData}  
          pagination={false}
        /> 
     )}
      <div style={{marginTop:'2%'}}></div>
      <Row justify="center" align="middle">  
        <Col>  
        <Form.Item>  
            <Button type="primary" size='small'  htmlType="submit" loading={uploading}>  
            {t('report.Next')}  
            </Button>  
        </Form.Item> 
        </Col>  
    </Row>   
    
    </Form>
    </Card>
    
    </div> 
  );  
};  
  
export default FileUpload;